package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * ClassName: TaskServiceImpl
 * Description:
 * date: 2023/8/15 0015 18:37
 *
 * @author zHan
 */

@Service
@Slf4j
@Transactional
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    @Autowired
    private CacheService cacheService;

    /**
     * 添加任务
     *
     * @param task 任务对象
     * @return 任务id
     */
    @Override
    public long addTask(Task task) {
        // 添加到数据库中
        boolean isSuccess = addTaskToDb(task);
        if (isSuccess) {
            // 添加到redis中
            addTaskToRedis(task);
        }
        return task.getTaskId();
    }

    /**
     * 添加到redis中
     *
     * @param task
     */
    private void addTaskToRedis(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();
        // 获取5分钟之后的时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        long nextScheduleTime = calendar.getTimeInMillis();
        // 如果执行时间 <= 当前时间，添加到list中
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
        } else if (task.getExecuteTime() <= nextScheduleTime) {
            // 如果执行时间 > 当前时间 且 <= 预设时间（5min），添加到zset
            cacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task),
                    task.getExecuteTime());
        }

    }

    /**
     * 添加到数据库中
     *
     * @param task
     * @return
     */
    private boolean addTaskToDb(Task task) {
        boolean flag = false;
        try {
            // 保存任务表
            Taskinfo taskInfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskInfo);
            taskInfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskInfo);

            // 添加taskId
            task.setTaskId(taskInfo.getTaskId());

            // 保存任务日志表
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(task, taskinfoLogs);
            taskinfoLogs.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);

            flag = true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return flag;
    }

    /**
     * 取消任务
     *
     * @param taskId
     * @return
     */
    @Override
    public boolean cancelTask(Long taskId) {
        boolean flag = false;

        // 根据taskId删除数据库中的任务
        Task task = updateDbTask(taskId, ScheduleConstants.CANCELLED);
        // 删除redis中的任务
        if (task != null) {
            removeTaskRedis(task);
            flag = true;
        }

        return flag;
    }

    /**
     * 删除redis中的任务
     *
     * @param task
     */
    private void removeTaskRedis(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();
        // 根据key删除redis中的数据
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(task));
        } else {
            cacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(task));
        }
    }

    /**
     * 删除数据库中的任务
     *
     * @param taskId
     * @param status
     * @return
     */
    private Task updateDbTask(Long taskId, int status) {
        Task task = null;
        try {
            // 删除任务表中的数据
            taskinfoMapper.deleteById(taskId);
            // 修改任务日志表中的数据
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);
            // 返回task对象
            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs, task);
            // 将Date转换为long
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        } catch (Exception e) {
            log.error("task cancel error{}", taskId);
            throw new RuntimeException(e);
        }
        return task;
    }


    /**
     * 根据类型和优先级拉取任务
     *
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task pullTask(Integer type, Integer priority) {
        Task task = null;
        try {
            // 从redis中拉取数据 pop
            String key = type + "_" + priority;
            String taskJson = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            if (StringUtils.isNotBlank(taskJson)) {
                task = JSON.parseObject(taskJson, Task.class);
                // 修改数据库
                updateDbTask(task.getTaskId(), ScheduleConstants.EXECUTED);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return task;
    }

    /**
     * 未来数据定时刷新，每分钟执行一次
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {
        // 添加分布式锁
        String token = cacheService.tryLock("FUTURE_TASK", 1000 * 3);
        if (StringUtils.isNotBlank(token)) {
            log.info("定时任务 --- 未来数据定时刷新");
            // 获取未来所有key的集合
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
            for (String futureKey : futureKeys) { // future_100_50
                // 创建topicKey
                String topicKey =
                        ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.TOPIC)[1];
                // 按照key和分值查询符合条件数据
                Set<String> tasks = cacheService.zRangeByScore(futureKey, 0,
                        System.currentTimeMillis());
                // 数据同步
                if (!tasks.isEmpty()) {
                    cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                    log.info("成功将{}刷新到{}", futureKey, topicKey);
                }
            }
        }
    }

    /**
     * 数据库任务同步到redis中
     */
    @Scheduled(cron = "0 */5 * * * ?")
    @PostConstruct  // 微服务启动之后先执行该方法
    public void reloadData() {
        clearCache();
        // 获取未来5min的数据
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        // 查询符合条件数据 -- 小于未来5min数据
        List<Taskinfo> taskInfoList =
                taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime,
                calendar));
        // 把任务添加到redis
        if (taskInfoList != null && taskInfoList.size() > 0) {
            taskInfoList.stream().forEach(taskinfo->{
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo,task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTaskToRedis(task);
            });
        }

        log.info("成功将数据库任务同步到redis中");
    }

    private void clearCache() {
        // 清理缓存中的数据 -- list、zset
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        cacheService.delete(topicKeys);
        cacheService.delete(futureKeys);
    }
}
